from db_connection import create_db_connection
from logger_config import logging

logger = logging.getLogger(__name__)


def query_data(config, table, query, params=None):
    """
    Query data from the database.

    Parameters:
        config (dict): Database configuration dictionary.
        table (str): Table name to query from.
        query (str): SQL query string.
        params (tuple, optional): Parameters for the SQL query.

    Returns:
        list: Query results or None if an error occurs.
    """
    cursor, connection = create_db_connection(config)
    if cursor and connection:
        sql = f"SELECT * FROM `{table}` WHERE {query}"
        try:
            cursor.execute(sql, params)
            result = cursor.fetchall()
            connection.commit()
            return result
        except Exception as e:
            logger.error(f"Query failed: {e}")
            return None
        finally:
            cursor.close()
            connection.close()


def insert_data(config, table, data):
    """
    Insert data into the database.

    Parameters:
        config (dict): Database configuration dictionary.
        table (str): Table name to insert into.
        data (dict): Data to insert, keys are column names and values are the data values.

    Returns:
        int: Number of affected rows or -1 if an error occurs.
    """
    cursor, connection = create_db_connection(config)
    if cursor and connection:
        columns = ', '.join(data.keys())
        placeholders = ', '.join(['%s'] * len(data))
        sql = f"INSERT INTO `{table}` ({columns}) VALUES ({placeholders})"
        try:
            cursor.execute(sql, tuple(data.values()))
            connection.commit()
            return cursor.rowcount
        except Exception as e:
            logger.error(f"Insert failed: {e}")
            return -1
        finally:
            cursor.close()
            connection.close()